package com.licheedev.adplayer;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.kk.taurus.playerbase.render.AspectRatio;
import com.kk.taurus.playerbase.widget.BaseVideoView;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class AdView extends FrameLayout {

    private static final String TAG = "AdView";

    public static final int SHOW_AD = 11;
    public static final int SHOW_LOADING = 12;
    public static final int SHOW_ERROR = 13;
    public static final int SHOW_NONE = 14;

    @IntDef(value = {
        SHOW_AD, SHOW_LOADING, SHOW_ERROR, SHOW_NONE
    })
    @Retention(RetentionPolicy.SOURCE)
    @interface ShowType {
    }

    @Nullable
    private final View mBackgroundView;
    private final BaseVideoView[] mVideos;
    private final ImageView[] mImages;
    private final View mLoadingView;
    private final View mErrorView;
    private final View[] mAdContentViews;

    /** 广告内容控件索引 */
    public final int mAdContentIndex;
    /** 是否启用首次播放时显示Loading布局 */
    public boolean enableFirstLoadingLayout = false;

    private int mCurrentVideo;
    private int mCurrentImage;

    public AdView(@NonNull Context context) {
        this(context, null);
    }

    public AdView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AdView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        int backgroundLayout = -1;
        int loadingLayoutId = R.layout.layout_loading_cover;
        int errorLayoutId = R.layout.layout_error_cover;
        int contentBgColor = Color.TRANSPARENT;

        //<enum name="centerCrop" value="0" />
        //<enum name="fitCenter" value="1" />
        //<enum name="center" value="2" />
        //<enum name="fitXY" value="3" />
        //<enum name="centerInside" value="4" />
        int imageScaleType = 3;

        //<enum name="aspect_ratio_16_9" value="0" />
        //<enum name="aspect_ratio_4_3" value="1" />
        //<enum name="aspect_ratio_match_parent" value="2" />
        //<enum name="aspect_ratio_fill_parent" value="3" />
        //<enum name="aspect_ratio_fit_parent" value="4" />
        //<enum name="aspect_ratio_origin" value="5" />
        //<enum name="aspect_ratio_fill_width" value="6" />
        //<enum name="aspect_ratio_fill_height" value="7" />
        int videoAspectRatio = 2;

        if (attrs != null) {
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AdView);

            backgroundLayout = ta.getResourceId(R.styleable.AdView_ad_background_layout, -1);

            loadingLayoutId =
                ta.getResourceId(R.styleable.AdView_ad_override_loading_layout, loadingLayoutId);

            errorLayoutId =
                ta.getResourceId(R.styleable.AdView_ad_override_error_layout, errorLayoutId);

            contentBgColor = ta.getColor(R.styleable.AdView_ad_content_bg_color, Color.TRANSPARENT);

            enableFirstLoadingLayout =
                ta.getBoolean(R.styleable.AdView_ad_enable_first_loading_layout,
                    enableFirstLoadingLayout);

            imageScaleType = ta.getInt(R.styleable.AdView_ad_image_scale_type, imageScaleType);
            videoAspectRatio =
                ta.getInt(R.styleable.AdView_ad_video_aspect_ratio, videoAspectRatio);

            ta.recycle();
        }

        if (backgroundLayout != -1) {
            mBackgroundView = LayoutInflater.from(context).inflate(backgroundLayout, this, false);
            addView(mBackgroundView);
        } else {
            mBackgroundView = null;
        }

        mAdContentIndex = mBackgroundView == null ? 0 : 1;
        BaseVideoView video1 = null;
        BaseVideoView video2 = null;
        try {
            // 视频1
            video1 = new BaseVideoView(context, attrs, defStyleAttr);
            applyVideoAspectRatio(video1, videoAspectRatio);
            video1.setBackgroundColor(contentBgColor);
            // 视频2
            video2 = new BaseVideoView(context, attrs, defStyleAttr);
            applyVideoAspectRatio(video2, videoAspectRatio);
            video2.setBackgroundColor(contentBgColor);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mVideos = new BaseVideoView[] { video1, video2 };

        // 图片1
        ImageView image1 = new ImageView(context, attrs, defStyleAttr);
        image1.setBackgroundColor(contentBgColor);
        applyImageScaleType(image1, imageScaleType);
        // 图片2
        ImageView image2 = new ImageView(context, attrs, defStyleAttr);
        image2.setBackgroundColor(contentBgColor);
        applyImageScaleType(image2, imageScaleType);
        mImages = new ImageView[] { image1, image2 };

        mAdContentViews = new View[] { video1, video2, image1, image2 };

        //// 加载布局
        mLoadingView = LayoutInflater.from(context).inflate(loadingLayoutId, this, false);
        addView(mLoadingView);
        //
        //// 错误布局
        mErrorView = LayoutInflater.from(context).inflate(errorLayoutId, this, false);
        addView(mErrorView);

        // 默认显示等待菊花
        switchView(SHOW_LOADING);
    }

    @Nullable
    public View getBackgroundView() {
        return mBackgroundView;
    }

    public View getLoadingView() {
        return mLoadingView;
    }

    public View getErrorView() {
        return mErrorView;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return true;
    }

    public void resetPlayerListener() {
        for (BaseVideoView video : mVideos) {
            video.setOnErrorEventListener(null);
            video.setOnPlayerEventListener(null);
        }
    }

    public void setVolume(float left, float right) {
        for (BaseVideoView video : mVideos) {
            video.setVolume(left, right);
        }
    }

    public void stop() {
        for (BaseVideoView video : mVideos) {
            video.stop();
        }
    }

    public void stopPlayback() {
        for (BaseVideoView video : mVideos) {
            video.stopPlayback();
        }
    }

    public void switchView(@ShowType int showType) {
        switch (showType) {
            case SHOW_AD:
                mLoadingView.setVisibility(GONE);
                mErrorView.setVisibility(GONE);
                break;
            case SHOW_LOADING:
                mLoadingView.setVisibility(VISIBLE);
                mErrorView.setVisibility(GONE);
                break;
            case SHOW_ERROR:
                mLoadingView.setVisibility(GONE);
                mErrorView.setVisibility(VISIBLE);
                break;
            default:
                mLoadingView.setVisibility(GONE);
                mErrorView.setVisibility(GONE);
                break;
        }
    }

    /** 把广告内容控件放置到广告控件位置 */
    public void moveContentViewToAdContentIndex(View contentView) {
        int currentIndex = indexOfChild(contentView);
        if (currentIndex < mAdContentIndex) {
            addView(contentView, mAdContentIndex);
        } else if (currentIndex > mAdContentIndex) {
            removeViewAt(currentIndex);
            addView(contentView, mAdContentIndex);
        }
    }

    public void makeOtherGone(View notGoneView) {
        for (View view : mAdContentViews) {
            if (view == notGoneView) {
                continue;
            }
            view.setVisibility(GONE);
        }
    }

    /** 当前播放控件 */
    public BaseVideoView currentVideoView() {
        return mVideos[mCurrentVideo];
    }

    /** 当前图片控件 */
    public ImageView currentImageView() {
        return mImages[mCurrentImage];
    }

    /** 所有视频控件 */
    public BaseVideoView[] getVideos() {
        return mVideos;
    }
    
    /** 所有图片控件 */
    public ImageView[] getImages() {
        return mImages;
    }

    private int getAnother(int current) {
        if (current == 0) {
            return 1;
        } else {
            return 0;
        }
    }

    public void changeVideoView() {
        mCurrentVideo = getAnother(mCurrentVideo);
    }

    public void changeImageView() {
        mCurrentImage = getAnother(mCurrentImage);
    }

    /** 设置图片缩放类型 */
    private static void applyImageScaleType(ImageView imageView, int imageScaleType) {
        //<enum name="centerCrop" value="0" />
        //<enum name="fitCenter" value="1" />
        //<enum name="center" value="2" />
        //<enum name="fitXY" value="3" />
        //<enum name="centerInside" value="4" />
        switch (imageScaleType) {
            case 0:
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                break;
            case 1:
                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                break;
            case 2:
                imageView.setScaleType(ImageView.ScaleType.CENTER);
                break;
            case 3:
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                break;
            case 4:
                imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                break;
        }
    }

    /**
     * 设置视频比例
     *
     * @param videoView
     * @param videoAspectRatio
     */
    private static void applyVideoAspectRatio(BaseVideoView videoView, int videoAspectRatio) {

        //<enum name="aspect_ratio_16_9" value="0" />
        //<enum name="aspect_ratio_4_3" value="1" />
        //<enum name="aspect_ratio_match_parent" value="2" />
        //<enum name="aspect_ratio_fill_parent" value="3" />
        //<enum name="aspect_ratio_fit_parent" value="4" />
        //<enum name="aspect_ratio_origin" value="5" />
        //<enum name="aspect_ratio_fill_width" value="6" />
        //<enum name="aspect_ratio_fill_height" value="7" />

        switch (videoAspectRatio) {
            case 0:
                videoView.setAspectRatio(AspectRatio.AspectRatio_16_9);
                break;
            case 1:
                videoView.setAspectRatio(AspectRatio.AspectRatio_4_3);
                break;
            case 2:
                videoView.setAspectRatio(AspectRatio.AspectRatio_MATCH_PARENT);
                break;
            case 3:
                videoView.setAspectRatio(AspectRatio.AspectRatio_FILL_PARENT);
                break;
            case 4:
                videoView.setAspectRatio(AspectRatio.AspectRatio_FIT_PARENT);
                break;
            case 5:
                videoView.setAspectRatio(AspectRatio.AspectRatio_ORIGIN);
                break;
            case 6:
                videoView.setAspectRatio(AspectRatio.AspectRatio_FILL_WIDTH);
                break;
            case 7:
                videoView.setAspectRatio(AspectRatio.AspectRatio_FILL_HEIGHT);
                break;
        }
    }
}
